import { ProForm, ProFormCaptcha, ProFormDependency, ProFormText } from "@ant-design/pro-components";
import React, { useState } from "react";
import { Form, Input, message, Modal } from "antd";
import { MOBILE_REGEXP, PASSWORD_REGEXP, USERNAME_REGEXP } from "common/utils/regexp";
import { vcodeV1ControllerSendMobileVcode } from "@/services/auto/vcode";
import { SendVcodeType } from "common/utils/data";
import { userV1ControllerCreate, userV1ControllerVerifyRegister } from "@/services/auto/user";
import { registerVcodeKeyStorage } from "@/utils/storage";

interface FormData extends API.UserCreateDto {
  password2: string;
}

function Register({onSuccess}:{onSuccess: ()=>void}){
  const [form] = ProForm.useForm<FormData>();

  const [mobilePassed, setMobilePassed] = useState<boolean>(false);

  return <ProForm size="large" onFinish={(values)=>{
    const {password2, ...restValues} = values;
    return userV1ControllerCreate({
      ...restValues,
      vcodeKey: registerVcodeKeyStorage.get(restValues.mobile) ?? undefined,
    }).then(()=>{
      message.success('注册成功，请登录');
      onSuccess();
      return true
    }).catch(()=>{
      return false;
    });
  }} form={form} submitter={{
    resetButtonProps: {
      style: {display: 'none'}
    },
    submitButtonProps: {
      block: true,
    },
  }}>
    <div className="mb-[16px] text-red-500">由于运营商报备问题，若您的手机为移动号码，存在验证码发送失败的情况，给您带来不便，敬请谅解</div>
    <ProForm.Item validateDebounce={1000} name="mobile" rules={[
      {
        validator: (_,value)=>{
          if(!MOBILE_REGEXP.test(value)){
            return Promise.reject('请输入正确格式的手机号');
          }
          return userV1ControllerVerifyRegister({
            mobile: value,
          }).then((res)=>{
            if(res.isExists){
              return Promise.reject('该手机号已存在');
            }else{
              setMobilePassed(true);
              return Promise.resolve();
            }
          }).catch((e)=>{
            return Promise.reject(e)
          })
        },
      },
    ]}>
      <Input placeholder={'手机号'} onChange={()=>{
        setMobilePassed(false);
      }} />
    </ProForm.Item>
    <ProFormDependency name={['mobile']}>
      {
        ({mobile})=>{
          return <ProFormCaptcha
            fieldProps={{
              maxLength: 6,
            }}
            captchaProps={{
              disabled: !MOBILE_REGEXP.test(mobile) || !mobilePassed
            }}
            placeholder={'6位验证码'}
            captchaTextRender={(timing, count) => {
              if (timing) {
                return `${count} ${'获取验证码'}`;
              }
              return '获取验证码';
            }}
            name="vcode"
            rules={[
              {
                required: true,
                message: '请输入6位验证码',
                max: 6,
                min: 6
              },
            ]}
            onGetCaptcha={async () => {
              const cacheVcodeKey = registerVcodeKeyStorage.get(mobile);

              const res = await vcodeV1ControllerSendMobileVcode({
                mobile,
                vcodeKey: cacheVcodeKey ?? undefined,
                type: SendVcodeType.USER_REGISTER,
              })

              if(res.vcodeKey === cacheVcodeKey){
                message.success('您的上次验证码还未失效，请直接使用');
              }else{
                registerVcodeKeyStorage.set(mobile, res.vcodeKey);
                message.success('获取验证码成功！');
              }

            }}
          />
        }
      }
    </ProFormDependency>
    <ProForm.Item
      name="name"
      validateDebounce={1000}
      rules={[
        {
          validator: (_,value)=>{
            if(!USERNAME_REGEXP.test(value)){
              return Promise.reject('请输入20位以内字符，只支持英文数字中文下划线中杠');
            }
            return userV1ControllerVerifyRegister({
              name: value,
            }).then((res)=>{
              if(res.isExists){
                setMobilePassed(false);
                return Promise.reject('该昵称已存在');
              }else{
                setMobilePassed(true);
                return Promise.resolve();
              }
            }).catch((e)=>{
              setMobilePassed(false);
              return Promise.reject(e)
            })
          },
        },
      ]}
    >
      <Input placeholder="昵称，不可修改" maxLength={20} />
    </ProForm.Item>
    <ProFormText.Password
      name="password"
      fieldProps={{
        maxLength: 20,
      }}
      placeholder="密码"
      rules={[
        {
          required: true,
          pattern: PASSWORD_REGEXP,
          message: '请填写6-20位密码，至少包含英文、数字、符号其中两种',
        },
      ]}
    />
    <ProFormText.Password
      name="password2"
      placeholder="确认密码"
      rules={[
        (form)=>{
          const password = form.getFieldValue('password');
          return {
            validator: (_, value,)=>{
              if(!value || value !== password){
                return Promise.reject('请填写确认密码，且与密码一致')
              }
              return Promise.resolve();
            },
          }
        },
      ]}
    />
  </ProForm>
}


export const openRegisterModal = ()=>{
  const modal =  Modal.info({
    title: '注册',
    icon: null,
    width: 600,
    footer: null,
    closable: true,
    content: <Register onSuccess={()=>{
      modal.destroy();
    }} />,
  })
  return modal;
}
